//
//  nearbyViewController.m
//  wtshoppingcite
//
//  Created by TW on 14-10-15.
//  Copyright (c) 2014年 TW. All rights reserved.
//

#import "nearbyViewController.h"
#import "ShoppingModel.h"
#import "NearTableViewCell.h"
#import "NearDetailViewController.h"
#import "BaseTableView.h"
#import "NetServiseCommonData.h"
#import "CustomTabItemView.h"
#import "CustomSearchTextField.h"
#import "MMDownMenu.h"
#import "NearByTableView.h"
#import "RegisterHelper.h"
#import "ShoppingDetailModel.h"
#import "ProductDetailModel.h"
#import "CitesModel.h"
#import "Request.h"
#import "ShopperModel.h"
#import "ShopperViewController.h"
#import "CommunityViewController.h"
#import "PoiSearchViewController.h"
#import "MobClick.h"

@interface nearbyViewController ()<MMDownMenuDelegate,UITextFieldDelegate,CustomTabItemViewDelegate,UITableViewEventsDelegate,NearByTableViewForAdvDelegate>
{
    
    NearByTableView *nearTableView;
    UIView *glassView;
    CustomTabItemView *tabItemView;
    NSString *pageNum;
    NSInteger x;
    NSInteger y;
    NSInteger z;
    Request* nearbyRequest;
    Request* shopRequest;
    Request* threeGounpRequest;

}
@property(nonatomic,strong) CustomSearchTextField* searchText;
@property (nonatomic, strong) NSMutableDictionary *conditionParamDic;
@property(nonatomic,strong) UIView* favShowView;

@end

@implementation nearbyViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setTitleView:@"小区附近商家"];
    
    _dataArray = [[NSMutableArray alloc]initWithCapacity:1];
    
    self.isBackButton = NO;
    self.navigationItem.leftBarButtonItem = nil;
    
    [RegisterHelper shareHelper].purchaseArray = [[NSMutableArray alloc]initWithCapacity:1];
    [RegisterHelper shareHelper].deleteArray = [[NSMutableArray alloc]initWithCapacity:1];
    
    self.view.backgroundColor = [UIColor clearColor];
   
    [self initWithView];

    nearTableView.index = 0;
    pageNum = @"0";
    nearTableView.scrollEnabled = YES;
//    [self getNearByWithData:NO];
    [self getShoppingList:NO];
    x = 1;
    y = 0;
    z = 0;
    // Do any additional setup after loading the view.
}

-(void)initWithView{

    tabItemView = [[CustomTabItemView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 45) type:TAB_ITEM_TYPE_DEFAULT];
    tabItemView.backgroundColor = COLOR_RGBA(245, 245, 245,1);
    tabItemView.delegate = self;
    [tabItemView initWithNearbyItemNames:@[@"安心商家",@"团购",@"社区生活圈"]];
    [self.view addSubview:tabItemView];
    
    
    nearTableView = [[NearByTableView alloc]initWithFrame:CGRectMake(0, tabItemView.bottom, kWidth, kHeight-64-64-20) style:UITableViewStylePlain];
    nearTableView.isNeedTorefresh = YES;
    nearTableView.index = 0;
    nearTableView.eventsDelegate = self;
    nearTableView.isMore = YES;
    [self.view addSubview:nearTableView];

}


#pragma mark  eventsDelegate
- (void)pullUp:(BaseTableView *)baseTableView{
    
//    if (x != 0) {
//         [self getNearByWithData:YES];
//    }else if (y != 0){
//        [self getShoppingList:YES];
//    }
    if (x != 0) {
        
        [self getShoppingList:YES];
    }
}

- (void)pullDown:(BaseTableView *)baseTableView{
    
     pageNum = @"0";
//    if (x != 0) {
//        [self getNearByWithData:NO];
//    }else if (y != 0){
//        [self getShoppingList:NO];
//    }

    if (x != 0) {
        
        [self getShoppingList:NO];
    }
}

-(void)tabItemSelectedAtIndex:(int)index tabItem:(CustomTabItemView *)view{
    [nearbyRequest cancel];
    [shopRequest cancel];
    [threeGounpRequest cancel];

    nearTableView.data =0;
    
    if (index == 0) {
        
       nearTableView.index = 0;
       pageNum = @"0";
       nearTableView.scrollEnabled = YES;
//       [self getNearByWithData:NO];
        
        [self getShoppingList:NO];
        x = 1;
        y = 0;
        z = 0;
        
    }else if (index == 1){
        
//        nearTableView.index = 1;
//        nearTableView.scrollEnabled = YES;
//        pageNum = @"0";
//        [self getShoppingList:NO];
//        x = 0;
//        y = 1;
//        z = 0;
        
        nearTableView.index = 1;
        nearTableView.scrollEnabled = NO;
        nearTableView.isMore = NO;
        
        UIView *bgView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, kWidth, 40)];
        bgView.backgroundColor = [UIColor whiteColor];
        nearTableView.tableFooterView = bgView;
        
        nearTableView.imageArray = @[@"food",@"hotel",@"entertain",@"movie",@"visit",@"liftService"];
        nearTableView.data = @[@"餐饮美食",@"生活服务",@"娱乐休闲",@"电影",@"旅游",@"精选"];
        [nearTableView reloadData];
        x = 0;
        y = 1;
        z = 0;
        
    }else if (index == 2){
        
        nearTableView.index = 2;
        nearTableView.scrollEnabled = YES;
        nearTableView.isMore = NO;
        nearTableView.isNeedTorefresh = NO;
        nearTableView.tableFooterView = nil;
        nearTableView.nearbyForAdvDelegate = self;
        nearTableView.data = [[NetServiseCommonData getAdvacePoiListData] objectForKey:@"list"];
        [nearTableView reloadData];
        x = 0;
        y = 0;
        z = 1;
        
    }
}

-(void)basetableView:(BaseTableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (nearTableView.index == 0) {
        
//        ShoppingModel *shoppingModel = _dataArray[indexPath.row];
//        
//        NearDetailViewController *nearDVC = [[NearDetailViewController alloc]init];
//        nearDVC.shoppingModel =shoppingModel;
//        nearDVC.hidesBottomBarWhenPushed = YES;
//        [self.navigationController pushViewController:nearDVC animated:YES];
        
        ShopperModel *shopperModel = self.dataArray[indexPath.row];
        
        ShopperViewController *shopperVC = [[ShopperViewController alloc]init];
        shopperVC.hidesBottomBarWhenPushed = YES;
        shopperVC.shopId = shopperModel.shopId;
        [self.navigationController pushViewController:shopperVC animated:YES];
        
    }else if (nearTableView.index == 1){
        
        CommunityViewController *communityVC = [[CommunityViewController alloc]init];
        communityVC.hidesBottomBarWhenPushed = YES;
        communityVC.index = indexPath.row;
        [self.navigationController pushViewController:communityVC animated:YES];
        
        
    }else if (nearTableView.index == 2){
        
        
    }
    
}

#pragma mark getShoppingList 安心商家
-(void)getShoppingList:(BOOL)isMore{
    
    NSString *page = pageNum;
    NSString *pageSize = @"10";
    NSString *cid = [[RegisterHelper shareHelper]citesId];
    
    __weak nearbyViewController *weak_self = self;
    NSMutableDictionary *listDic = [NSMutableDictionary dictionary];
   
    SetValueForKey(listDic, cid, @"cid");
    SetValueForKey(listDic, page, @"page");
    SetValueForKey(listDic, pageSize, @"pageSize");
    
    [self showLoadImageView:self.view subview:nearTableView];
    shopRequest = [NetWorkService byRequestWithAPIPrefix:kBaseAppUrl
                              andAPISuffix:kshoplist
                             andHttpMethod:@"POST"
                             andParameters:listDic
                           andRequestCache:NO
                            andUseParamDic:YES
                       andPostDataEncoding:MKNKPostDataEncodingTypeJSON
                     andRequestFinishBlock:^(BYRequest *request, BYResponse *response) {
                        [nearTableView doneLoadingTableViewData];
                        [self performSelector:@selector(dismissLoadImageView) withObject:nil afterDelay:0.5];
                        
                         request.requestCache = YES;
                         
                         if (response.isError) {
                             
                             DLog(@"error %@",response.errorMessage);
                             
                         }else{
                             
                             NSDictionary *responseDic = request.responseJSON;
                             DLog(@"成功数据:%@",responseDic);
                             
                             NSArray *list = [responseDic objectForKey:@"list"];
                             if (list.count < 10) {
                                 nearTableView.isMore = NO;
                             }else{
                                 nearTableView.isMore = YES;
                                 
                                 int currentPage = [pageNum intValue];
                                 pageNum = [NSString stringWithFormat:@"%d",currentPage+1];
                                 
                             }
                             if (!isMore) {
                                 [_dataArray removeAllObjects];
                             }
                             for (NSDictionary *dic in list) {
                                 ShopperModel *shoppingModel = [[ShopperModel alloc]initWithShopperInfo:dic];
                                 [_dataArray addObject:shoppingModel];
                             }
                             nearTableView.data = _dataArray;
                             [RegisterHelper shareHelper].type = PurchaseSingleStyle;
                         }
                         
                         [nearTableView reloadData];
                     }];
    
}


#pragma mark getNearByWithData E团购
-(void)getNearByWithData:(BOOL)isMore{
    
    NSString *cid = [[RegisterHelper shareHelper]citesId];
    NSString *page = pageNum;
    NSString *pageSize = @"10";
    
    __weak nearbyViewController *weak_self = self;
    NSMutableDictionary *listDic = [NSMutableDictionary dictionary];
    //SetValueForKey(listDic, typeId, @"typeId");
    SetValueForKey(listDic, cid, @"cid");
    SetValueForKey(listDic, page, @"page");
    SetValueForKey(listDic, pageSize, @"pageSize");
    
    [self showLoadImageView:self.view subview:nearTableView];
    nearbyRequest = [NetWorkService byRequestWithAPIPrefix:kBaseAppUrl
                              andAPISuffix:kgrouplist
                             andHttpMethod:@"POST"
                             andParameters:listDic
                           andRequestCache:NO
                            andUseParamDic:YES
                       andPostDataEncoding:MKNKPostDataEncodingTypeJSON
                     andRequestFinishBlock:^(BYRequest *request, BYResponse *response) {
                         [nearTableView doneLoadingTableViewData];
                         [self performSelector:@selector(dismissLoadImageView) withObject:nil afterDelay:0.5];
                         
                         request.requestCache = YES;
                         
                         if (response.isError) {
                             
                             DLog(@"error %@",response.errorMessage);
                             
                         }else{
                             
                             NSDictionary *responseDic = request.responseJSON;
                             DLog(@"成功数据:%@",responseDic);
                             
                             NSArray *list = [responseDic objectForKey:@"list"];
                             if (list.count < 10) {
                                 nearTableView.isMore = NO;
                             }else{
                                 nearTableView.isMore = YES;
                                 
                                 int currentPage = [pageNum intValue];
                                 pageNum = [NSString stringWithFormat:@"%d",currentPage+1];
                                 
                             }
                             if (!isMore) {
                                 [_dataArray removeAllObjects];
                             }
                             for (NSDictionary *dic in list) {
                                 ShoppingModel *shoppingModel = [[ShoppingModel alloc]initWithNearInfo:dic type:ShopTableDataStyleEShop];
                                 [_dataArray addObject:shoppingModel];
                             }
                             [RegisterHelper shareHelper].type = PurchaseGroupStyle;
                             nearTableView.data = _dataArray;
                         }
                         [nearTableView reloadData];
                     }];
}


-(void)viewWillAppear:(BOOL)animated{
    
    [super viewWillAppear:animated];
    [MobClick beginLogPageView:@"PageOne"];
    //[self startRequestDataWithCode];
    
//    pageNum = @"0";
//    if (x == 1) {
//        
//        [self getNearByWithData:NO];
//        
//    }else if (y == 1){
//        
//        [self getShoppingList:NO];
//        
//    }
    
}

- (void)viewWillDisappear:(BOOL)animated
{
    
    [super viewWillDisappear:animated];
    [MobClick endLogPageView:@"PageOne"];
    
}

#pragma mark 获取小区信息
-(void)startRequestDataWithCode{
   
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    [params setValue:@"440300" forKey:@"cityCode"];
    
    [NetWorkService byRequestWithAPIPrefix:kBaseAppUrl
                              andAPISuffix:kcites
                             andHttpMethod:@"POST"
                             andParameters:params
                           andRequestCache:NO
                            andUseParamDic:YES
                       andPostDataEncoding:MKNKPostDataEncodingTypeJSON
                     andRequestFinishBlock:^(BYRequest *request, BYResponse *response) {
                         if(!response.isError){
                             NSDictionary *responseDic = request.responseJSON;
                             
                             BOOL result = [[responseDic objectForKey:@"result"] boolValue];
                             if (result == 0) {
                                 DLog(@"数据获取成功 %@",responseDic);
                                 NSArray *list = [responseDic objectForKey:@"list"];
                                 
                                 for (NSDictionary *dic in list) {
                                     
                                     CitesModel *citesModel = [[CitesModel alloc]initWithCitesInfo:dic];

                                 }
                                 
                             }
                         }
                         else{
                             
                             DLog(@"获取数据失败  %@",response.errorMessage);
                         }

                     }];
}

#pragma mark nearbyTableView Delegate
-(void)nearBySelectAdvCellWithRowData:(NSDictionary *)data withIndex:(NSInteger)index{
    
     NSArray* titles = [data objectForKey:@"names"];
    
    NSLog(@"点击了第%d个",index);
    PoiSearchViewController *poiSearchVC = [[PoiSearchViewController alloc]init];
    poiSearchVC.hidesBottomBarWhenPushed = YES;
    poiSearchVC.keyText = titles[index];
    [self.navigationController pushViewController:poiSearchVC animated:YES];
}

#pragma mark chooneAction
-(void)chooseAction{
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
